import 'package:filetest/appglobal.dart';
import 'package:flutter/cupertino.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

class FileUtils {
  static FileUtils shared = FileUtils._instance();
  FileUtils._instance();
  ///getExternalStorageDirectory()：获取存储卡目录，仅支持Android；
  /// 找到正确的本地路径
  /// getApplicationDocumentsDirectory 类似iOS的NSDocumentDirectory和Android上的AppData目录

  get androidPackagePath async {
    if(Platform.isAndroid){
      final directory = await getExternalStorageDirectory();
      return directory!.path;
    }else{
      return null;
    }
  }

  get localDocPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  /// getTemporaryDirectory 类似iOS的NSTemporaryDirectory和Android的getCacheDir
  get localTempPath async {
    final directory = await getTemporaryDirectory();
    return directory.path;
  }

  ///创建文件夹
  setFileFolder(String path) async{
   try{
     Directory directory =  Directory(path);
     if (!directory.existsSync()) {
       directory.createSync();
       debugPrint('文件夹初始化成功，文件保存路径为 ${directory.path}');
     }
     else {
       debugPrint('文件夹已存在');
     }
   }catch(e){
     e.toString();
   }
  }

  ///创建文件
  setFile(String path) {
    File file = File(path);
    if (!file.existsSync()) {
      file.createSync();
      debugPrint('创建成功');
    } else {
      debugPrint('文件已存在');
    }
    return file;
  }

  /// 将数据写入文件
  void writeContent(String path, String content, {mode=FileMode.append}) async{
    // Write the file
    File file = await setFile(path);
    try {
      file.writeAsStringSync(content,mode: mode);

      debugPrint('文件写入成功');
    } catch (e) {
      debugPrint('文件写入失败');
    }
  }

  /// 从文件中读取数据
  readContent(String path) async {
    File file = await setFile(path);
    try {
      // Read the file
      String contents = file.readAsStringSync();
      debugPrint('文件读取成功:$contents');
      return contents;
    } catch (e) {
      debugPrint('文件读取失败');
      return '';
    }
  }

  ///文件/文件夹删除
  deleteFileFolder(String path) {
    Directory directory =  Directory(path);
    if (directory.existsSync()) {
      List<FileSystemEntity> files = directory.listSync();
      if (files.isNotEmpty) {
        for (var file in files) {
          file.deleteSync();
        }
      }
      directory.deleteSync();
      debugPrint('文件夹删除成功');
    }
  }

  ///删除文件
  deleteFile(String path) {
    File file =  File(path);
    if (file.existsSync()) {
      try {
        file.deleteSync();
        debugPrint('文件删除成功');
      } catch (e){
        debugPrint('文件删除失败');
      }
    }
  }

  ///遍历所有文件
  getAllSubFile(String path) async{
    Directory directory = Directory(path);
    if (directory.existsSync()) {
      return directory.listSync();
    }
    return [];
  }

  //判断文件是否存在
  Future<bool> judgeFileExist(String path)async{
    File file =  File(path);
    if(file.existsSync()){
      return true;
    }
    return false;

  }

  //写buiness日志

  writeBuiness(String content)async{
    try{
      String path = AppGlobal.currentDayLogPath+"/buiness.txt";
      File file = File(path);
      if(!file.existsSync()){
        //创建文件
        await setFile(path);
      }
      //写入内容
      writeContent(path,content+"\n");
    }catch(e){
      e.toString();
    }

  }

  //写异常日志
  writeException(String content)async{
    try{
      String path = AppGlobal.currentDayLogPath+"/exception.txt";
      File file = File(path);
      if(!file.existsSync()){
        //创建文件
        await setFile(path);
      }
      //写入内容
      writeContent(path,content+"\n");
    }catch(e){
      e.toString();
    }
  }

  //写网络日志
  writeNetWork(String content)async{
    try{
      String path = AppGlobal.currentDayLogPath+"/network.txt";
      File file = File(path);
      if(!file.existsSync()){
        //创建文件
        await setFile(path);
      }
      //写入内容
      writeContent(path,content+"\n");
    }catch(e){
      e.toString();
    }
  }
  //读取文件所有内容
  Future<String> readFileAllContent(String path)async{
    try{
      File file = File(path);
      if(file.existsSync()){
        String content = await readContent(path);
        return content;
      }
      return "";
    }catch(e){
      e.toString();
      return "";
    }
  }
  //根据键读取文件内容
  Future<String> readKeyValue(String path,String key)async{
    String value = "";
    try{
      File file = File(path);
      if(file.existsSync()){
        String content  = await readContent(path);
        if(content.isEmpty){
          return value;
        }
        if(!content.contains("=")){
          return value;
        }
        if(!content.contains(key)){
          return value;
        }

        List<String> contentList = content.split("\n");
        if(contentList.isNotEmpty){
          for (var contentData in contentList) {
            if(contentData.isNotEmpty&&contentData.contains("=")){
              List<String> contentDataList = contentData.split("=");
              if(contentDataList.isNotEmpty&&contentDataList.length>1&&contentDataList[0].trim()==key){
               return contentDataList[1].trim();
              }
            }

          }
        }
      }
      return value;
    }catch(e){
      e.toString();
      return value;
    }
  }

  //根据键写入文件内容
  Future<bool> writeKeyValue(String path,String key,String value)async{

    try{
      File file = File(path);
      if(file.existsSync()){
        String content  = await readContent(path);
        if(content.isEmpty){
          return false;
        }
        if(!content.contains("=")){
          return false;
        }
        if(!content.contains(key)){
          return false;
        }

        List<String> contentList = content.split("\n");
        if(contentList.isNotEmpty){
          for (var contentData in contentList) {
            if(contentData.isNotEmpty&&contentData.contains("=")){
              List<String> contentDataList = contentData.split("=");
              if(contentDataList.isNotEmpty&&contentDataList.length>1&&contentDataList[0].trim()==key){
                content = content.replaceFirst(contentDataList[1], " "+value);
                writeContent(path, content,mode:FileMode.write);
                return true;
              }
            }

          }
        }
      }

    }catch(e){
      e.toString();

    }
    return false;
  }

}